<template>
	<view class="hwq-content">
		<navBar :title="porjectName" :title2="areaName+'/'+siteName">
			<!-- <u-icon name="plus" color="#2979ff" size="20" @click="uploadFile"></u-icon> -->
		</navBar>
		<view class="searchBox">
			<searchCom class="search-input" v-model="searchText" @enter="filterDataList" @change="filterDataList"></searchCom>
			<u-icon name="plus" color="#2979ff" size="20" @click="uploadFile"></u-icon>
		</view>
		<view class="top-box">
			<u-row justify="space-between">
				<u-col span="2">
					<view class="top-item" @click="crearteReport">
						<image src="/subpackage-emergency/static/Group+2207.png" alt="" class="top-image">
							<view class="top-name">创建报告</view>
					</view>
				</u-col>
				<u-col span="2">
					<view class="top-item" @click="positionMarker">
						<image src="/subpackage-emergency/static/Group+2208.png" alt="" class="top-image">
							<view class="top-name">位置标记</view>
					</view>
				</u-col>
				<u-col span="2">
					<view class="top-item" @click="materialInspection">
						<image src="/subpackage-emergency/static/temp.png" alt="" class="top-image">
							<view class="top-name">物资检查</view>
					</view>
					<!-- <view class="top-item" @click="fileOutPath">
						<image src="/static/image/emergency/Group%202209.png" alt="" class="top-image">
							<view class="top-name">文件外链</view>
					</view> -->
				</u-col>
				<u-col span="2">
<!-- 					<view class="top-item" @click="positionOutPath">
						<image src="/static/image/emergency/Group%202210.png" alt="" class="top-image">
							<view class="top-name">定位外链</view>
					</view> -->
				</u-col>
			</u-row>
		</view>
		<scroll-view scroll-y="true" class="main-box hwq-scroll-box hwq-is-search ">
			<view class="main-item" @click="returnLastLevel" v-if="currNode&&currNode.parent">
				<view class="icon-return-box">
					<u-icon name="more-dot-fill"></u-icon>
				</view>
				<view class="doc-name-box">
					<view class="doc-name">返回上一层</view>
				</view>
			</view>
			<view class="main-item" v-for="item in tableData" :key="item.id" @click="tableClick(item)">
				<image src="/subpackage-emergency/static/Group+2220.png" class="doc-icon-box" v-if="!item.fileName">
				</image>
				<image src="/subpackage-emergency/static/Group+2271.png" class="doc-icon-box" v-else></image>
				<view class="doc-name-box">
					<view class="doc-name">{{item.name}}</view>
					<view class="time">{{item.recordCreateDateText}}</view>
				</view>
				<view class="right-box">
					<view class="icon-box">
						<u-icon name="arrow-right" v-if="!item.fileName"></u-icon>
					</view>
					<view class="username-box">
						<!-- <image src="/static/image/login/user2.png" class="user-icon"></image> -->
						<view class="user-name">{{item.userName||item.updateUser}}</view>
					</view>
				</view>
			</view>
		</scroll-view>
	</view>
</template>

<script>
	import searchCom from "@/components/searchCom.vue"
	import pathObj from "@/config/index.js"
	import {
		getDocList,
		getDocSave,
		getUploadFile,
		getDocDelete,
		getAttachList,
		getDocDeleteAttach,
	} from "@/api/emergency/polling.js"
	import { getStationGetBySiteId } from "@/api/baseManage/baseManage.js"
	import { mapMutations } from "vuex"


	import mixins from "@/utils/mixins.js"

	import {
		getSiteSave
	} from "@/api/projectName/projectName"

	import {
		getToken
	} from '@/utils/auth'
import {
	uploadFile
} from '@/utils/request'
	export default {
		onLoad(option) {		
			this.siteObj = JSON.parse(option.siteRow)
			console.log(option, this.siteObj);
			this.id = this.siteObj.id
			this.porjectName = String(option.porjectName)
			this.areaName = String(option.areaName)
			this.workName = String(option.workName)
			this.siteName = String(this.siteObj.name)
			this.getList()
			uni.$on('refreshData',() => {
					this.getList();
				})
		},
		mixins: [mixins],
		data() {
			return {
				searchText: undefined,
				porjectName: "",
				areaName: "",
				workName:'',
				siteName: "",
				tableData: [],
				currNode: undefined,
				siteObj: {},
				stationObj: null
			}
		},
		components: {
			searchCom
		},
		onShow() {
			this.getStationSite()
		},
		methods: {
			...mapMutations('emergency',['GET_SITEOBJ']),
			uploadFile() {
				uni.chooseImage({
					success: async (chooseImageRes) => {
						const tempFilePaths = chooseImageRes.tempFilePaths;
						let fileList = tempFilePaths.map(item => ({
							url: item
						}))
						for (let item of fileList) {
							let formData = {}
							if (this.currNode.docId) {
								formData.docId = this.currNode.docId
							}
							// this.form.siteId = this.siteId
							let data = await uploadFile({
								url: "rest/doc/uploadDoc",
								formData,
								filePath: item.url
							})
							let res = JSON.parse(data)
							if (!res.success) return
							this.currNode.docId = res.result.id
						}
						// let data = await uploadFile({
						// 	url: "rest/doc/uploadDoc",
						// 	formData,
						// 	files: fileList.map(item => ({
						// 		name: "attach",
						// 		uri: item.url
						// 	}))
						// })
						// data = JSON.parse(data)
						// if (!data.success) return
						// if (!this.currNode.docId) {
						// 	this.currNode.docId = data.result.id
						// }
						let res = await getDocSave(this.currNode)
						this.$message("上传成功", {
							icon: 'success'
						})
						this.getDocumentList(this.currNode)
					}
				});
			},
			//点击位置外链
			positionOutPath() {
				//http://139.9.41.8:8001/cdsa-link/#/?token=1b70338c-802c-4d7a-bb27-8698b04c6b27&siteId=170&page=updateAddress
				uni.share({
					provider: 'weixin',
					type: 1,
					title: "分享上传文件地址",
					summary: this.$config.SHARE_URL + `?token=${getToken()}&siteId=${this.id}&page=updateAddress`,
					success:()=>{
						this.$message("分享成功", {
							icon: "success"
						})
					},
					fail:()=> {
						this.$message("分享失败", {
							icon: "fail"
						})
					}
				})
			},
			//点击文件外链
			fileOutPath() {
				//http://139.9.41.8:8001/cdsa-link/#/?token=1b70338c-802c-4d7a-bb27-8698b04c6b27&docId=173&id=485&page=updateFile
				uni.share({
					provider: 'weixin',
					type: 1,
					title: "分享上传文件地址",
					summary: this.$config.SHARE_URL +
						`?token=${getToken()}&docId=${this.currNode.docId}&id=${this.currNode.id}&page=updateFile`,
					success:()=>{
						this.$message("分享成功", {
							icon: "success"
						})
					},
					fail:()=>{
						this.$message("分享失败", {
							icon: "fail"
						})
					}
				})
			},
			//点击创建报告
			crearteReport() {
				let id = this.id
				let documentId = this.currNode.id
				uni.navigateTo({
					url: `/subpackage-emergency/pages/inspection/createReport?id=${id}&documentId=${documentId}&porjectName=${this.porjectName}&areaName=${this.areaName}&workName=${this.workName}`,
					events: {
						// 为指定事件添加一个监听器，获取被打开页面传送到当前页面的数据
						refreshList: () => {
							this.getDocumentList(this.currNode)
						},
					},
				})
			},
			//点击位置标记
			positionMarker() {
				let position = this.siteObj.position || ""
				let address = this.siteObj.address || ""
				let data = position+","+address
				uni.navigateTo({
					url: `/subpackage-emergency/pages/inspection/map?position=${data}`,
					events: {
						setPosition: this.setPosition
					}
				})
			},
			setPosition(data) {
				console.log(data, '1828');
				// #ifdef APP-PLUS
					const address = data.data.data[0].action.address
					const position = data.data.data[0].action.position
				// #endif
					
				// #ifdef MP-WEIXIN
					const address = data.data[data.data.length - 1].action.address
					const position = data.data[data.data.length - 1].action.position 
				// #endif
				this.siteObj = {
					...this.siteObj,
					address,
					position,
				}
				this.GET_SITEOBJ(this.siteObj)
				let obj = {
					id: this.id,
					address,
					position,
					projectId:uni.getStorageSync('isOwner')
				}
				console.warn(obj,'33366666')
				getSiteSave(obj).then(data => {
					if (data.success) {
						this.$message("标记成功")
					}
				})
			},

			returnLastLevel() {
				// if(this.breadcrumbList.length<=1) return 
				// this.breadcrumbList.pop()
				// if(!this.currNode?.parent) return
				// this.currNode = this.currNode.parent
				// this.getDocumentList(this.breadcrumbList[this.breadcrumbList.length-1])
				this.getDocumentList(this.currNode = this.currNode.parent)
			},

			getList() {
				let _data = {
					siteId: this.id,
					treeLevel: 1,
					parentId: null
				}
				getDocList(_data).then(res => {
					if (res.success) {
						// this.breadcrumbList = res.result
						// this.row = res.result
						this.currNode = res.result[0]
						this.getDocumentList({...res.result[0]})
						// this.reset()
					}
				})
			},

			async getDocumentList({
				id: parentId,
				docId,
				fileName,
				siteId
			}) {
				let tree = null
				const res = await getDocList({
					parentId,
					fileName,
					siteId: parentId ? undefined : siteId
				})
				let fileList = res.result || []
				let fileListMap = {}
				fileList.forEach(value => {
					value.updateUser = value.userName ?? value.updateUser
					value.name = value.name ?? value.originalFileName
					value.recordCreateDateText = this.getDate2(value.recordCreateDate)
					value.recordUpdateDateText = this.getDate2(value.recordUpdateDate)
					fileListMap[value.id] = true
				})
				if (docId) {
					const res2 = await getAttachList({
						docId
					})
					res2.result.forEach(value => {
						value.name = value.originalFileName
						value.recordCreateDateText = this.getDate2(value.recordCreateDate)
						value.recordUpdateDateText = this.getDate2(value.recordUpdateDate)
						if (!fileListMap[value.id]) {
							fileList.push(value)
						}
					})
					// fileList.push(...res2.result)
				}
				this.tableData = fileList
			},
			// 表格行的双击事件
			tableClick(tree) {
				console.log(tree,'tree');
				//判断双击的是文件
				if (tree.fileName) {
					// 有 fileName 就是文件
					// 判断是 文件 还是 图片
					// contentType.split("/")[0] === "image" 就是图片
					if(tree.contentType.split("/")[0] === "image"){
						console.log(pathObj.DOWNLOAD_FILE_URL);
						let url = pathObj.DOWNLOAD_FILE_URL + tree.fileName
						// 预览图片
						uni.previewImage({
							urls: [ url ],
							longPressActions: {
								success: function(data) {
									console.log(data,'data');
								},
								fail: function(err) {
								}
							}
						});
					}else{
						// 文件 预览  先下载文件到本地, 再打开文件
						let url = pathObj.DOWNLOAD_FILE_URL + tree.fileName
						// 下载文件
						uni.downloadFile({
							url: url,
							success: function(res) {
								var filePath = res.tempFilePath;
								// 打开文件
								uni.openDocument({
									filePath: filePath,
									showMenu: true,
									success: function (res) {
										console.log('打开文档成功', res);
									  }
								});
							},
						})
					}
				} else {
					tree.parent = this.currNode
					this.currNode = tree
					this.getDocumentList(tree)
				}

			},
			
			// 物资检查
			materialInspection(){
				if(this.stationObj){
					uni.navigateTo({
						url: `/subpackage-emergency/pages/inspection/materialsInspection?stationId=${this.stationObj.id || null}&siteId=${this.id || null}&riskState=${this.stationObj.riskState || null}&worksCategory=${this.stationObj.worksCategory || null}`,
					})
				}else{
					uni.showToast({
						title:'当前工点没有项目应急点',
						icon:"none"
					})
				}
			},
			
			// 判断工点有没有绑定基地
			async getStationSite(){
				let res = await getStationGetBySiteId({siteId: this.id})
				console.warn(this.id,'----369')
				this.stationObj = res.result || null
				console.log(res,'xx');
				// getStationGetBySiteId
			},
			filterDataList(fileName) {
				this.getDocumentList({
					...this.currNode,
					fileName,
					id: fileName ? undefined : this.currNode.id,
					docId: fileName ? undefined : this.currNode.docId
				})
			}
		}
	}
</script>

<style lang="scss" scoped>
	.hwq-content {
		/* #ifdef MP-WEIXIN */
			padding-top: 200rpx;
		/* #endif */
		.top-box {
			padding: 44rpx 44rpx 0;

			.top-item {
				display: flex;
				flex-direction: column;
				align-items: center;

				.top-image {
					width: 92rpx;
					height: 92rpx;
				}

				.top-name {
					font-size: 24rpx;
					font-family: PingFang SC-Medium, PingFang SC;
					color: #42536A;
					line-height: 32rpx;
					margin-top: 10rpx;
				}
			}
		}

		.searchBox{
			display: flex;
			align-items: center;
			.search-input {
				flex: 1;
				padding-right: 20rpx;
				::v-deep .searchBox {
					padding-bottom: 0px;
				}
			}
		}

		.main-box {
			height: calc(100% - 370rpx) !important;

			.main-item {
				display: flex;
				align-items: center;
				border-bottom: 2rpx solid #E2E5ED;
				padding: 20rpx 0;

				.doc-icon-box {
					flex: 1;
					max-width: 68rpx;
					height: 68rpx;
					margin-right: 30rpx;
				}

				.icon-return-box {
					width: 68rpx;
					text-align: center;
					margin-right: 30rpx;
				}

				.doc-name-box {
					flex: 1;

					.doc-name {
						font-size: 32rpx;
						font-family: PingFang SC-Bold, PingFang SC;
						font-weight: bold;
						color: #445469;
						line-height: 56rpx;
					}

					.time {
						font-size: 26rpx;
						font-family: PingFang SC-Medium, PingFang SC;
						color: #6A819E;
						line-height: 30rpx;
					}
				}

				.right-box {
					flex: 1;
					max-width: fit-content;
					text-align: right;

					.username-box {
						display: flex;

						.user-icon {
							max-width: 48rpx;
							height: 48rpx;
							border-radius: 50%;
						}

						.user-name {
							font-size: 26rpx;
							font-family: PingFang SC-Medium, PingFang SC;
							color: #6A819E;
							line-height: 48rpx;
							margin-left: 20rpx;
						}
					}
				}
			}
		}
	}
</style>